package com.chen.schedule.controller;

import com.chen.schedule.pojo.SysUser;
import com.chen.schedule.service.SysUserService;
import com.chen.schedule.service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 接收所有已user开头的请求
@WebServlet(value = "/user/*", loadOnStartup = 6)
public class SysUserController extends BaseController {
    private SysUserService userService;

    @Override
    public void init() throws ServletException {
        userService = new SysUserServiceImpl();
    }

    /**
     * 注册
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接口请求参数
        String username = req.getParameter("username");
        String userPwd = req.getParameter("userPwd");
        // 封装成一个SYSUser对象
        SysUser user = new SysUser();
        user.setUsername(username);
        user.setUserPwd(userPwd);
        // 调用service层 返回1 代表成功 0 代表失败
        Integer rows = userService.save(user);
        if (rows > 0) {
            // 使用响应重定向来进行页跳转提示
            resp.sendRedirect("/registSuccess.html");
        } else {
            resp.sendRedirect("/registFail.html");
        }

    }

    /**
     * 用户登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接口请求参数
        String username = req.getParameter("username");
        String userPwd = req.getParameter("userPwd");
        // 封装成一个SYSUser对象
        SysUser user = new SysUser();
        user.setUsername(username);
        user.setUserPwd(userPwd);
        // 调用service层
        Integer status = userService.login(user);
        // 0 代表用户名不存在 1 代表密码错误 2登录成功
        if (status == 0) {
            resp.sendRedirect("/loginUsernameError.html");
        } else if (status == 1) {
            resp.sendRedirect("/loginUserPwdError.html");
        } else {
            // 登录成功 将用户名放入session中
//            System.out.println(user);
            req.getSession().setAttribute("username", username);
            resp.sendRedirect("/showSchedule.html");
        }
    }
}
